﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace MyLib.MyHelper
{
    public static class MyHelper
    {
        // 发送get请求(HttpClient方式)
        public static async Task<string> HttpGetDataByHttpClient(string url, Dictionary<string, string> headers = null)
        {
            var http = new HttpClient();
            // 加入请求头
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    http.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
            }
            // 发送请求
            var resp = await http.GetAsync(url);
            if (resp.IsSuccessStatusCode)
            {
                var resp_content = await resp.Content.ReadAsStringAsync();
                return resp_content;
            }

            return null;
        }

        // 发送post请求(HttpClient方式)
        public static async Task<string> HttpPostDataByHttpClinet(string url, Dictionary<string, string> post_data, Dictionary<string, string> headers = null)
        {
            var http = new HttpClient();

            // 加入post数据 
            var post_content = new FormUrlEncodedContent(post_data);
            post_content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");

            // 加入请求头
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    post_content.Headers.Add(header.Key, header.Value);
                }
            }

            // 发送数据
            var resp = await http.PostAsync(url, post_content);

            if (resp.IsSuccessStatusCode)
            {
                var resp_content = await resp.Content.ReadAsStringAsync();
                return resp_content;
            }

            return null;
        }

        // 发送get请求(HttpWebRequest方式)
        public static string HttpGetByHttpWebRequest(string url, Dictionary<string, string> headers = null)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";

                // 添加请求头
                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        request.Headers.Add(header.Key, header.Value);
                    }
                }

                using (WebResponse response = request.GetResponse())
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                        {
                            return reader.ReadToEnd();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"请求出错: {ex.Message}");
                return null;
            }
        }

        // 发送post请求(HttpWebRequest方式)
        public static string HttpPostByHttpWebRequest(string url, string postData = null, Dictionary<string, string> headers = null)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";

                // 添加请求头
                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        request.Headers.Add(header.Key, header.Value);
                    }
                }

                if (!string.IsNullOrEmpty(postData))
                {
                    byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                    request.ContentLength = byteArray.Length;
                    using (Stream dataStream = request.GetRequestStream())
                    {
                        dataStream.Write(byteArray, 0, byteArray.Length);
                    }
                }

                using (WebResponse response = request.GetResponse())
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                        {
                            return reader.ReadToEnd();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"请求出错: {ex.Message}");
                return null;
            }
        }

        // 取中间文本批量
        public static List<string> GetMidTextBatch(string sourceText, string leftMarker, string rightMarker, bool ignoreCase = false, int maxTextLength = 0, string prefix = "", string suffix = "", bool includeLeftMarker = false, bool includeRightMarker = false, int startPosition = 0)
        {
            List<string> extractedTexts = new List<string>();
            int startPos = startPosition;
            while (true)
            {
                int foundStart = FindIndex(sourceText, leftMarker, startPos, ignoreCase);
                if (foundStart == -1)
                {
                    break;
                }
                startPos = foundStart + leftMarker.Length;

                int foundEnd = FindIndex(sourceText, rightMarker, startPos, ignoreCase);
                if (foundEnd == -1)
                {
                    break;
                }
                int middleLength = foundEnd - startPos;
                string searchText = sourceText.Substring(startPos, middleLength);
                searchText = prefix + searchText + suffix;
                if (includeLeftMarker)
                {
                    searchText = leftMarker + searchText;
                }
                if (includeRightMarker)
                {
                    searchText = searchText + rightMarker;
                }
                if (maxTextLength == 0 || searchText.Length < maxTextLength)
                {
                    extractedTexts.Add(searchText);
                }
                startPos = foundEnd + rightMarker.Length;
            }
            return extractedTexts;
        }

        private static int FindIndex(string source, string marker, int start, bool ignoreCase)
        {
            try
            {
                if (source == null || marker == null)
                {
                    return -1;
                }
                StringComparison comparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
                return source.IndexOf(marker, start, comparison);
            }
            catch (Exception)
            {
                return -1;
            }
        }

        // 取中间文本
        public static string GetMidText(string str, string leftStr, string rightStr, bool ignoreCase = false)
        {
            try
            {
                StringComparison comparison = StringComparison.CurrentCulture;

                if (ignoreCase)
                {
                    comparison = StringComparison.OrdinalIgnoreCase;
                }

                if (str == null || leftStr == null || rightStr == null)
                {
                    return null;
                }

                int index = str.IndexOf(leftStr, comparison);
                if (index == -1) return "";

                int i = index + leftStr.Length;

                int last = str.IndexOf(rightStr, i, comparison);

                if (last == -1) return "";

                return str.Substring(i, last - i);
            }
            catch (Exception)
            {
                return null;
            }
        }

        // 取左边文本
        public static string GetLeft(string str, string mark_str, bool ignoreCase = false)
        {
            StringComparison comparison = StringComparison.CurrentCulture;

            if (ignoreCase)
            {
                comparison = StringComparison.OrdinalIgnoreCase;
            }

            int index = str.IndexOf(mark_str, comparison);
            if (index == -1) return "";

            return str.Substring(0, index);
        }

        // 取右边文本
        public static string GetRight(string str, string mark_str, bool ignoreCase = false)
        {
            StringComparison comparison = StringComparison.CurrentCulture;

            if (ignoreCase)
            {
                comparison = StringComparison.OrdinalIgnoreCase;
            }

            int index = str.LastIndexOf(mark_str, comparison);
            if (index == -1) return "";

            int index_start = index + mark_str.Length;

            int end_len = str.Length - index_start;
            string temp = str.Substring(index_start, end_len);
            return temp;
        }

        /// <summary>
        /// 匹配文本
        /// </summary>
        /// <param name="regStr">正则
        /// <param name="text">源方本
        /// <param name="lable">返回的标签
        /// <returns></returns>
        public static string RegMatch(string regStr, string text, string lable)
        {
            Regex r = new Regex(regStr);
            Match m = r.Match(text);
            if (!m.Success) return "";
            return m.Groups[lable].ToString();
        }

        // 将指定内容写入到指定路径的txt文件中(如果文件不存在则创建，如果存在则覆盖内容。)
        public static void WriteToTxtFile(string filePath, string content)
        {
            try
            {
                using (StreamWriter writer = new StreamWriter(filePath))
                {
                    writer.WriteLine(content);
                }
            }
            catch (IOException e)
            {
                Debug.WriteLine($"写入文件时出错: {e.Message}");
            }
        }

        // 将指定内容追加到指定路径的txt文件中(如果文件不存在则创建。)
        public static void AppendToTxtFile(string filePath, string content)
        {
            try
            {
                using (StreamWriter writer = new StreamWriter(filePath, true))
                {
                    writer.WriteLine(content);
                }
            }
            catch (IOException ex)
            {
                Debug.WriteLine($"写入文件时出错: {ex.Message}");
            }
        }

        /// <summary>
        /// QQ发送邮件
        /// </summary>
        /// <param name="fromEmail"> 发件的QQ邮箱
        /// <param name="fromPassword"> 密码或者授权码
        /// <param name="toEmail"> 收件的邮箱
        /// <param name="title"> 邮件标题
        /// <param name="content"> 邮件内容
        /// <returns></returns>
        public static bool QQSendEmail(string fromEmail, string fromPassword, string toEmail, string title, string content)
        {

            MailMessage message = new MailMessage();
            message.From = new MailAddress(fromEmail);

            message.To.Add(toEmail);
            message.Subject = title;

            // 创建包含图片的 HTML 内容
            string htmlBody = content;

            AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlBody, null, "text/html");

            message.AlternateViews.Add(htmlView);

            SmtpClient client = new SmtpClient("smtp.qq.com", 587);
            client.EnableSsl = true;
            client.Credentials = new NetworkCredential(fromEmail, fromPassword);

            try
            {
                client.Send(message);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
